<?php

/**
 * @author tuannguyen2042
 * @copyright 2014
 */

function __startsWith($haystack, $needle) {
  $length = strlen($needle);
  return (substr($haystack, 0, $length) === $needle);
}

function __endsWith($haystack, $needle) {
  $length = strlen($needle);
  $start = $length * -1; //negative
  return (substr($haystack, $start) === $needle);
}

function getLatLong($address) {
  $prepAddr = str_replace(' ','+',$address);
  $geocode = file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.urlencode($prepAddr).'&sensor=false');
  $output = json_decode($geocode);
  $latitude = $output->results[0]->geometry->location->lat;
  $longitude = $output->results[0]->geometry->location->lng;
  return $latitude . ',' . $longitude;
}

?>

<script type="text/javascript">
  var aho;
  var aho2;
  var TrainStations, BusStops,SubWays,NearbyPlaces;
  var glob;
  var output='';
  
  function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
    var R = 6371; // Radius of the earth in km
    var dLat = deg2rad(lat2-lat1);  // deg2rad below
    var dLon = deg2rad(lon2-lon1);
    var a =
      Math.sin(dLat/2) * Math.sin(dLat/2) +
      Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
      Math.sin(dLon/2) * Math.sin(dLon/2);
    
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    var d = R * c; // Distance in km
    return Math.round(d*100)/100;
  }

  function deg2rad(deg) {
    return deg * (Math.PI/180)
  }
  
  var nearby;
  var request;
  var counter = 1;

  var result;
  var marker;
  var service;
  var map;
  var directionsService = new google.maps.DirectionsService();
  var directionsDisplay = new google.maps.DirectionsRenderer();

  function GetDirections(){    
    var latlng='<?php echo $listing["Listing"]["latlng"]; ?>';
    latlng = latlng.split(',');   
      
    var address=document.getElementById('address').value;
    var selectedMode = document.getElementById('mode').value;
    var request = { origin: address, 
                    destination: new google.maps.LatLng(latlng[0],latlng[1]),
                    travelMode: google.maps.TravelMode[selectedMode]
                  };

    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
      }
    });
  }
  
  function initialize() {
    var mapOptions = {
            center: new google.maps.LatLng(51.4924186,-0.2609205),
            zoom: 8,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
    map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
    
    // BEGIN DIRECTIONS          
    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById('panel'));             
    // END DIRECTIONS

    var geocoder = new google.maps.Geocoder();
    var start;
    map.setZoom(11);
    var infowin;
              
    var map2 = new google.maps.Map(document.getElementById('sv'), mapOptions);      
    var latlng = '<?php echo $listing["Listing"]["latlng"]; ?>';
    latlng = latlng.split(',');
      
    var panoramaOptions = {
      position: new google.maps.LatLng(latlng[0],latlng[1]),
      pov: {
        heading: 34,
        pitch: 10
      }
    };
    
    var panorama = new  google.maps.StreetViewPanorama(document.getElementById('sv'),panoramaOptions);
    map2.setStreetView(panorama);   
    
    start = '<?php echo $listing['Listing']['address_1']; ?>';

    geocoder.geocode( { 'address': start}, function(results2, status) {
        setTimeout('', 100);
        if (status == google.maps.GeocoderStatus.OK) {
          <?php
            $out = '<div id="listing-rate" style="vertical-align: middle;padding-bottom: 2px;padding-top: 2px;width: 165px">';
            if ((($i_AVGRating * 2) % 2) == 0) {
              $i_MaxEn = $i_AVGRating;
              $i_MaxDis = 5 - $i_MaxEn;
              $b_Half = false;
            } else {
              $i_MaxEn = $i_AVGRating - 0.5;
              $i_MaxDis = 5 - ($i_MaxEn + 1);
              $b_Half = true;
            }
            
            for ($i = 0; $i < $i_MaxEn; $i++){
              $out = $out . '<img src="' . SITE_WEBROOT . 'img/stars_enabled.png" width="15"/>';
            }
            
            if ($b_Half){
              $out = $out . '<img src="' . SITE_WEBROOT . 'img/stars_half.png" width="15"/>';
            }
            
            for ($i = 0; $i < $i_MaxDis; $i++){
              $out = $out . '<img src="' . SITE_WEBROOT . 'img/stars_disabled.png" width="15"/>';
            }
    
            $out = $out . '<span style="float: right;">&nbsp;&nbsp;' . $i_TotalReview . ' мнения</span>';
            $out = $out . '<br/>' . $listing['Listing']['address_1'];
            $out = $out . '<div style="clear: both;"></div>';
            $out = $out . '</div>';

            $out = str_replace('"', "'", $out);

            $link = '<a href="' . SITE_WEBROOT . $listing["Listing"]["url_title"] . '-l' . $listing["Listing"]["id"] . '.html">' . htmlspecialchars($listing["Listing"]["title"]) . '</a>';
            $link = str_replace('"', "'", $link);
          ?>

          infowin = new google.maps.InfoWindow({
            content:"<div class='wam-googft-info-window'><?php echo $link; ?><br><?php echo $out; ?></div>"
          });
          
          marker = new google.maps.Marker({ map: map});
          marker.setVisible(false);
          /*google.maps.event.addListener(marker, 'click', function() {
                infowin.open(map,marker);
            });*/
          map.setCenter(results2[0].geometry.location);
          marker.setPosition(results2[0].geometry.location);
          marker.setVisible(true);
        } else {
          
        }
    });
               
    <?php
      $number = 1;
      foreach ($listings as $listing):
        $link = $number.'&nbsp;<a href="' . SITE_WEBROOT . $listing["Listing"]["url_title"] . '-l' . $listing["Listing"]["id"] . '.html">' . htmlspecialchars($listing["Listing"]["title"]) . '</a>';
        $link = str_replace('"', "'", $link);
        
        $out = '<div id="listing-rate" style="vertical-align: middle;padding-bottom: 2px;padding-top: 2px;width: 165px">';
        if ((($i_AVGRating * 2) % 2) == 0) {
          $i_MaxEn = $i_AVGRating;
          $i_MaxDis = 5 - $i_MaxEn;
          $b_Half = false;
        } else {
          $i_MaxEn = $i_AVGRating - 0.5;
          $i_MaxDis = 5 - ($i_MaxEn + 1);
          $b_Half = true;
        }
        
        for ($i = 0; $i < $i_MaxEn; $i++){
          $out = $out . '<img src="' . SITE_WEBROOT . 'img/stars_enabled.png" width="15"/>';
        }
        
        if ($b_Half){
          $out = $out . '<img src="' . SITE_WEBROOT . 'img/stars_half.png" width="15"/>';
        }
        
        for ($i = 0; $i < $i_MaxDis; $i++){
          $out = $out . '<img src="' . SITE_WEBROOT . 'img/stars_disabled.png" width="15"/>';
        }
        
        $out = $out . '<span style="float: right;">&nbsp;&nbsp;' . $i_TotalReview . ' мнения</span>';
        $out = $out . '<br/>' . $listing['Listing']['address_1'];
        $out = $out . '<div style="clear: both;"></div>';
        $out = $out . '</div>';

        $out = str_replace('"', "'", $out);
      ?>

      
      start = '<?php echo $listing['Listing']['address_1']; ?>';
      var latlng = '<?php echo $listing["Listing"]["latlng"]; ?>';
      latlng = latlng.split(',');   
           
      var number = <?php echo $number; $number++; ?>;
      marker = new google.maps.Marker({ 
                            map: map,
                            icon:'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld='+ number +'|FF776B|000000',
                            //position:results2[0].geometry.location
                            position:new google.maps.LatLng(latlng[0],latlng[1])
                        });
      
      var contentstr="<div class='wam-googft-info-window'><?= $link ?><br><?= $out ?></div>";
      marker.content=contentstr;
      marker.setVisible(false);
      var veh_infowindow = new google.maps.InfoWindow({content:contentstr});

      google.maps.event.addListener(marker, 'click', function() {
        veh_infowindow.setContent(this.content);
        veh_infowindow.open(map,this);
      });
      
      //map.setCenter(results2[0].geometry.location);
      map.setCenter(new google.maps.LatLng(latlng[0],latlng[1]));
      // marker.setPosition(results2[0].geometry.location);
      marker.setVisible(true);

    <?php endforeach; ?>
  }
  google.maps.event.addDomListener(window, 'load', initialize);
</script>

<style type="text/css">
    #map-canvas { height: 200px; }
</style>

<?php
if(!isset($this->params['named']['ind']) && empty($this->params['named']['ind'])){ ?>

  <div class="listings">
    <table cellspacing="0" cellpadding="5" width="100%">
      <?php
        $i = 0;
        $pagenum = $this->Paginator->params();
        $pagenum = $pagenum['page'];
        $pagenum = $pagenum - 1;
        $iiii = 0;
        foreach ($listings as $listing):
          $kk = ($pagenum * 10) + ($iiii + 1);
          $iiii = $iiii+1;
          $class = null;
          if ($i++ % 2 == 0) {
            $class = ' class="altrow"';
          }
        ?>
      
        <tr<?php echo $class; ?>>
          <td valign="top" style="padding-right: 5px; width: 125px;">
            <div class="preview" style="margin-bottom: 10px;">
              <img src="http://open.thumbshots.org/image.pxf?url=<?php echo urlencode($listing["Listing"]["url"]); ?>" alt="<?php echo htmlspecialchars($listing["Listing"]["url"]); ?>" />
            </div>
          </td>
          <td valign="top" style="padding-right: 5px;">
            <div class="title">
              <?php echo $kk.'.&nbsp;&nbsp;<a href="' . SITE_WEBROOT . $listing["Listing"]["url_title"] . '-l' . $listing["Listing"]["id"] . '.html">' . htmlspecialchars($listing["Listing"]["title"]) . '</a>'; ?>
              <br/>
              <?php 
                $last_but_one = count($listing["Listing"]["all_urls"]);
                $last_but_one = $last_but_one - 2;

                $category_last = end(explode('/',$listing["Listing"]["all_urls"][$last_but_one]['url']));
                $india_url = $listing["Listing"]["all_urls"][0]['url'];
                $nagpur = $india_url.$category_last;
              ?>
              Categories:  <?php echo $listing["Listing"]["all_urls"][$last_but_one]['name'];  ?> in 
              <a href="<?php echo SITE_WEBROOT .$nagpur ; ?>" ><?php echo htmlspecialchars($listing["Listing"]["all_urls"][0]['name']); ?></a>&nbsp;/&nbsp;
              <a href="<?php echo SITE_WEBROOT . $listing["Listing"]["all_urls"][$last_but_one]['url']; ?>" ><?php echo htmlspecialchars($listing["Listing"]["all_urls"][1]['name']); ?></a><br/>
              
              <?php
                echo "Telephone: ".$listing["Listing"]["landline"]."<br/>";
                echo "Address : ";
                if( trim($listing['Listing']['address_1']) != ""){
                  echo $listing['Listing']['address_1'];
                }
                
                if( trim($listing['Listing']['address_2']) != ""){
                  echo $listing['Listing']['address_2'];
                }
                
                $rr = $listing['Listing']['review_rate'];
                $upperL = ceil($rr);
                $lowerL = floor($rr);
                $half = false;
                if( $upperL != $lowerL){
                  $half = true;
                }

                echo "<br/>";
                echo "Total Review: ";
                
                for ($i = 0; $i < 5; $i++) {
                  if( $i< $lowerL ) {
                    echo '<img src="' . SITE_WEBROOT . 'img/stars_enabled.png" width="15"/>';
                  } else if ( $half ){
                    echo '<img src="' . SITE_WEBROOT . 'img/stars_half.png" width="15"/>';
                  } else {
                    echo '<img src="' . SITE_WEBROOT . 'img/stars_disabled.png" width="15"/>';
                  }
                }
                echo "&nbsp;&nbsp;".$listing['Listing']['review_c'];
              ?>
            </div>
            <div class="url"><?php echo htmlspecialchars($listing["Listing"]["url"]); ?></div>
            <p><?php echo $htmlToText->html2text($listing["Listing"]["description"], 160, true); ?></p>
            
            <?php
              $ts = explode('<br/>',$listing['Listing']['train_stations']);
              $bs = explode('<br/>',$listing['Listing']['bus_stations']);
              $ss = explode('<br/>',$listing['Listing']['subway_stations']);
            ?>
              
            <?php if (($ts[0] !== '')): ?>
              <strong>Train Station</strong>
              <div><?php echo $ts[0]; ?></div>
            <?php endif; ?>
               
            <?php if (($bs[0] !== '')): ?>
              <strong>Bus Station</strong>
              <div><?php echo $bs[0]; ?></div>
            <?php endif; ?>
            
            <?php if (($ss[0] !== '')): ?>
              <strong>Subway Station</strong>
              <div><?php echo $ss[0]; ?></div>
            <?php endif; ?>                            

          </td>
        </tr>
      <?php endforeach; ?>
    </table>
  </div>
  
<?php } else { ?>
  
  <div class="listings">
    <table cellspacing="0" cellpadding="5" width="100%">
      <?php
        $i = 0;
        $pagenum = $this->Paginator->params();
        $pagenum = $pagenum['page'];
        $pagenum = $pagenum - 1;

        foreach ($listings as $listing):
          $kk = ($pagenum * 10) + ($i + 1);
          $class = null;
          if ($i++ % 2 == 0) {
            $class = ' class="altrow"';
          }
      ?>
      
      <tr<?php echo $class; ?>>
        <td valign="top" style="padding-right: 5px; width: 0px;">
          <!--   
          <div class="preview" style="margin-bottom: 10px;">
            <img src="http://open.thumbshots.org/image.pxf?url=<?php echo urlencode($listing["Listing"]["url"]); ?>" alt="<?php echo htmlspecialchars($listing["Listing"]["url"]); ?>" />
          </div> 
          -->
        </td>
        <td valign="top" style="padding-right: 5px;">
          <div class="title">
            <?php echo $kk.'.&nbsp;&nbsp;<a href="' . SITE_WEBROOT . $listing["Listing"]["url_title"] . '-l' . $listing["Listing"]["id"] . '.html">' . htmlspecialchars($listing["Listing"]["title"]) . '</a>'; ?>
          </div>
          <div class="url"><?php echo htmlspecialchars($listing["Listing"]["url"]); ?></div>          
        </td>
      </tr>
      <?php endforeach; ?>
    </table>
  </div>
  
<?php } ?>

<!-- PAGING -->
<br />
<p>
<?php
  echo $this->Paginator->counter(array('format' => __('Page %page% of %pages%, showing %current% records out of %count% total, starting on record %start%, ending on %end%', true)));
?>	
</p>


<div class="paging">
<?php  
  $pageOptions = $this->Paginator->params(); //var_dump($pageOptions);
  if (isset($this->params['named']['ind']) && !empty ($this->params['named']['ind'])) {
    $ind = "/ind:".$this->params['named']['ind'];
  } else {
    $ind = "";
  }

  $tttoo = $pageOptions['page'] / 4;
  $start_pp = 1;
  if($tttoo > 1 ){
    $start_pp = $pageOptions['page'] - 4;
  }
  
  $prev = $pageOptions['page'] - 1;
  if($prev < 1) {
	 $prev = '';
  }

  $next_pages = $pageOptions['pageCount'];
  $end_pp = $pageOptions['page'] + 4;

  if( $end_pp > $next_pages ){
	 $end_pp = $pageOptions['pageCount'];
  } 
  
  $next_pa = $end_pp + 1;
  if( $next_pa > $pageOptions['pageCount'] ) {
    $next_pa = '';	
  }

  if( isset($prev) && !empty($prev) ) {
    echo "<< <a href='http://".$_SERVER['SERVER_NAME'].Router::url('/').implode('/', $this->params['pass']).$ind."/page:".$prev."' >Previous</a> ";
  } else {
    echo "<< Previous ";
  }   

  for( $i = 1; $i <= $pageOptions['pageCount'] ; $i++ ){
    if( $i >= $start_pp && $i <= $end_pp ) {
		  if( $i == $pageOptions['page']) {
		    echo $i." | ";
		  } else {
		    echo '<a href="javascript:void(0);" onclick="filterListings('.$i.')">'.$i.'</a> | ';
		  }
    }
  }

  if( isset($next_pa) && !empty($next_pa) ) {
    echo " <a href='http://".$_SERVER['SERVER_NAME'].Router::url('/').$locationname.$ind."/page:".$next_pa."' >Next</a> >>";
  } else {
    echo " Next >>";
  }

   
  echo "<br/>";
  $a = range("A", "Z");
  foreach($a as $char) {
    if(in_array($char, $links_p)) {      
      echo '<a href="javascript:void(0)" onclick="filterListings('.$pageOptions['page'].',\''.$char.'\')">'.$char.'</a> ';
    } 
    else {
	   echo $char.'&nbsp;';
    }
  }
  
  //end
?>
</div>

<?php echo $this->element('sql_dump'); ?>
      